package com.example.auth.component;

import com.example.auth.beans.SecurityUser;
import org.springframework.beans.BeanUtils;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yang
 * desction:  如果我想在 JWT 中加入额外的字段(比方说用户的其他信息)怎么办呢，当然可以。spring security oauth2 提供了 TokenEnhancer 增强器。其实不光 JWT ，RedisToken 的方式同样可以
 */
@Component
public class JwTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Object principal = oAuth2Authentication.getPrincipal();
        SecurityUser securityUser = new SecurityUser();
        BeanUtils.copyProperties(principal,securityUser);
        Map<String, Object> info = new HashMap<>();
        info.put("jwt-ext", "JWT 扩展信息");
        info.put("userName", securityUser.getUsername());
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        System.out.println("增强扩展。。。。。。。。。。。。。。。。");
        return oAuth2AccessToken;
    }
}